package com.nc.util;

import java.sql.*;

/**
 * @author Administrator
 * @create 2020-07-28 10:19
 * @desc 工具类
 **/
public class DBUtil {
    /**
     * 打开数据库连接
     * @return conn
     */
    public static Connection getConnection(){
        Connection conn = null;
        String URL = "jdbc:mysql://127.0.0.1/person?characterEncoding=utf-8";
        String USER = "root";
        String PWD = "123123";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            try {
                conn = DriverManager.getConnection(URL,USER,PWD);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭数据库连接
     * @param rs
     * @param ps
     * @param conn
     */
    public static void close(ResultSet rs, PreparedStatement ps, Connection conn){
        try {
            if (rs != null){
                rs.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            if (ps != null){
                ps.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            if (conn != null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //增删改
    public static boolean update(String sql, Object ... prram) throws SQLException {
        boolean result=false;
        //增删改两件套
        Connection conn = getConnection();
        PreparedStatement ps = null;
        try{
            //获取执行对象
            ps = conn.prepareStatement(sql);
            //给占位符赋值
            for(int i = 0;i<prram.length;i++){
                ps.setObject(i+1,prram[i]);
            }
            //执行sql语句
            result = ps.executeUpdate() > 0;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            close(null,ps,conn);
        }
        return result;
    }
}
